package com.itgone.easyblog.service.image.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.log.StaticLog;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.itgone.easyblog.config.BlogServiceException;
import com.itgone.easyblog.service.image.IFileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class AliyunFileService implements IFileUploadService {
    private static final String ACCESS_KEY = "LTAI5tQMPYG2qQKF55dC5tvS";

    private static final String SECRET_KEY = "kcIIH02ixWYHuKpU457zE2DMrIvWh4";

    private static final String BUCKET_NAME = "joolun-ws";

    private static final String SERVER_BASE_URL = "http://aliyun.oss.itgone.com/";

    @Override
    public String upload(MultipartFile uploadFile) {
        String objectName = getRandomName(uploadFile.getOriginalFilename());
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        // 设置是否支持CNAME。CNAME用于将自定义域名绑定到目标Bucket。
        conf.setSupportCname(true);
        OSS ossClient = new OSSClientBuilder().build(SERVER_BASE_URL, ACCESS_KEY, SECRET_KEY, conf);

        try {
            InputStream inputStream = uploadFile.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            ResponseMessage response = result.getResponse();
            if (200 != response.getStatusCode()) {
                throw new RuntimeException();
            }
            return response.getUri();
        } catch (Exception ex) {
            StaticLog.error("文件上传失败", ex);
            throw new BlogServiceException("文件上传失败");
        }
    }

    @Override
    public int deleteByUrl(String url) {
        return 1;
    }

    private String getRandomName(String originalFilename) {
        String mainName = FileUtil.mainName(originalFilename);
        String uuid = UUID.fastUUID().toString(true);
        return originalFilename.replace(mainName, uuid);
    }
}
